// index.js
// 获取应用实例
var common = require("../../../public.js");
const QRCode = require('../../../utils/weapp-qrcodes.js')
const app = getApp()
Page({
    data: {
        detaiList: [], //详情列表
        top: "",
        value: '',
        flag: 2, //假设1是已购买 2是未购买
        gouList: [], //热卖会员卡
        showView: true,
        isRuleTrue: false,
        userInfo: null,
        nianList: [], //我购买的会员卡的列表
        nianList_two: [],
        objs: {},
        id: "",
        weiGou: [], //没有购买的
        ites: {},
        pagecount: 1,
        totalArr: [], //分页总数据
        yiGou: [],
        ids: "",
        stars: 3,
        sho: false,
        actives: '0',
        active: 0,
        flag_tab: true, //是否显示我的
        times: "", //到期时间
        showCode: false,
        cardImage: '',
        topp: 50,
        scrollTop: 0,
        username: '',
        cardnum: '',
        captchaId: 'fb6455d8a495496f8780b3c0aed5ea85',
        validate: '',
        merchantPhone: ''
    },
    //关闭规则提示
    hideRule: function () {
        this.setData({
            isRuleTrue: false
        })
    },
    onChangess(event) {
        // event.detail 为当前输入的值
        this.setData({
            username: event.detail
        })
    },
    onChanges(event) {
        console.log(event.detail);
        this.setData({
            cardnum: event.detail
        })

    },
    click_sub() {
        if (common.isEmptyString(this.data.username)) {
            common.showToast('请输入姓名')
            return
        }
        if (common.isEmptyString(this.data.cardnum)) {
            common.showToast('请输入身份证号')
            return
        }
        this.selectComponent('#captcha').popup() //验证码登录
    },
    // 验证码验证结果回调
    handlerVerify_normal: function (ev) {
        var that = this
        console.log('ev:', ev)
        if (!ev.detail[0]) {
            // 验证成功
            console.log('validate:', ev.detail[1])
            that.setData({
                validate: ev.detail[1]
            })
            this.submit(ev.detail[1])

        } else {
            // 验证失败
            wx.showToast({
                title: '验证失败',
                icon: 'success',
                duration: 2000
            })
        }
    },

    submit(validateCode) {
        const that = this
        const tempJson = {
            realName: that.data.username,
            cardNo: that.data.cardnum,
            userId: that.data.userInfo.id,
            token: that.data.token,
            validateCode: validateCode
        }
        // common.post('/user/verify', tempJson, function (res) {
        common.post('/user/verifyUseValidate', tempJson, function (res) {
            console.log(that.data.validate)
            if (res.status === 200) {
                wx.showToast({
                    title: '认证成功',
                    success: function () {
                        common.showLoginPage()

                    }
                })
            } else {

                common.showRequestErrMsg(res)


            }
        }, _ => {
            that.selectComponent('#captcha').reset()
        })
    },
    /**监听滚动定位 */
    onScroll(event) {
        wx.createSelectorQuery()
            .select('#scroller')
            .boundingClientRect((res) => {
                this.setData({
                    scrollTop: event.detail.scrollTop,
                });
            }).exec();
    },

    detais(e) {
        let {
            cardId,
            productType
        } = e.currentTarget.dataset.item
        let b = this.data.nianList.find(item => item.annualCardId == cardId);
        wx.navigateTo({
            url: '/pages/nianDetail/nianDetail?cardId=' + cardId +
                '&productType=' + productType +
                '&item=' + JSON.stringify(b),
        })
    },
    onClickHideCode() {
        this.setData({
            showCode: false
        });
    },
    // 底部弹出层s
    showPopup(e) {
        let {
            item
        } = e.currentTarget.dataset
        item['storeTypeName'] = item.pid_name
        common.gotoStore(item)
    },

    // 点击预约
    onClickShow(e) {
        var that = this
        var item = e.currentTarget.dataset.item
        this.setData({
            objs: e.currentTarget.dataset.item
        }, () => {
            // this.checkLoginToJump('/pages/realIdent/index')
            if (item.cardProductType == 1) {
                if (this.data.userInfo.isRealname) { //判断是否实名
                    app.globalData.cardId = item.cardId
                    app.globalData.discount = item.discount
                    app.globalData.productprice = item.productPrice
                    // common.toRealName('/pages/realIdent/index')
                    // 购买的预约x
                    wx.navigateTo({
                        url: '/pages/goYuyue/yuYue/index?productId=' + that.data.objs.productId +
                            '&cardId=' + that.data.objs.cardId +
                            '&productType=' + that.data.objs.productType +
                            '&cardProductType=' + item.cardProductType,
                    })

                } else {
                    common.toRealName('/pages/realIdent/index')
                }
                return
            }
            if (e.currentTarget.dataset.item.surplusUse == -1) {
                if (item.surplusUse == -1 && item.nowOrderStatus == 2 || item.surplusUse == -1 && item.nowOrderStatus == 5) {
                    if (item.nowOrderStatus == 1 && item.needReserve == 0 ||
                        item.nowOrderStatus == 3 && item.needReserve == 0 ||
                        item.nowOrderStatus == 6 && item.needReserve == 0 ||
                        item.nowOrderStatus == 7 && item.needReserve == 0 ||
                        item.nowOrderStatus == 8 && item.needReserve == 0) {
                        item.statusNames = '预约'
                        wx.navigateTo({
                            url: '/pages/goYuyue/yuYue/index?productId=' + that.data.objs.productId +
                                '&cardId=' + that.data.objs.cardId +
                                '&productType=' + that.data.objs.productType,
                        })
                    } else if (item.needReserve == 1 && item.nowOrderStatus == 1) {
                        item.statusNames = '去使用'
                        if (this.data.userInfo && this.data.userInfo.isRealname) {
                            wx.navigateTo({
                                url: '/packageA/pages/indexnian/qrcode/qrcode?cardId=' +
                                    item.cardId + '&productId=' +
                                    item.productId + '&imgCard=' + that.data.cardImage +
                                    '&imgurl=' + item.productImage +
                                    '&productName=' + item.productName +
                                    '&pid_name=' + item.pid_name +
                                    '&productType=' + item.productType,
                            })
                        } else {
                            this.setData({
                                isRuleTrue: true
                            })
                        }
                    } else if (item.needReserve == 1 && item.nowOrderStatus == 10) {
                        item.statusNames = '去使用'
                        if (this.data.userInfo && this.data.userInfo.isRealname) {
                            wx.navigateTo({
                                url: '/packageA/pages/indexnian/qrcode/qrcode?cardId=' +
                                    item.cardId + '&productId=' +
                                    item.productId + '&imgCard=' + that.data.cardImage +
                                    '&imgurl=' + item.productImage +
                                    '&productName=' + item.productName +
                                    '&pid_name=' + item.pid_name +
                                    '&productType=' + item.productType,
                            })
                        } else {
                            this.setData({
                                isRuleTrue: true
                            })
                        }
                    } else if (item.nowOrderStatus == 2 && item.needReserve == 0) {
                        item.statusNames = '去核销'
                        wx.navigateTo({
                            url: '/pages/ScenicArea/CardETicket/index?orderNo=' + item.orderNo,
                        })
                    } else if (item.nowOrderStatus == 5) {
                        item.statusNames = '去评价'
                        wx.navigateTo({
                            url: '/pages/ScenicArea/NianCardOrder/Cardcomment/Cardcomment?orderNo=' + item.orderNo,
                        })
                    } else if (item.nowOrderStatus == 10 && item.needReserve == 0) {
                        item.statusNames = '预约'
                        wx.navigateTo({
                            url: '/pages/goYuyue/yuYue/index?productId=' + that.data.objs.productId +
                                '&cardId=' + that.data.objs.cardId +
                                '&productType=' + that.data.objs.productType,
                        })
                    } else if (item.nowOrderStatus == null && item.needReserve == 0) {
                        item.statusNames = '预约'
                        wx.navigateTo({
                            url: '/pages/goYuyue/yuYue/index?productId=' + that.data.objs.productId +
                                '&cardId=' + that.data.objs.cardId +
                                '&productType=' + that.data.objs.productType,
                        })
                    } else if (item.nowOrderStatus == null && item.needReserve == 1) {
                        item.statusNames = '去使用'
                        if (this.data.userInfo && this.data.userInfo.isRealname) {

                            wx.navigateTo({
                                url: '/packageA/pages/indexnian/qrcode/qrcode?cardId=' +
                                    item.cardId + '&productId=' +
                                    item.productId + '&imgCard=' + that.data.cardImage +
                                    '&imgurl=' + item.productImage +
                                    '&productName=' + item.productName +
                                    '&pid_name=' + item.pid_name +
                                    '&productType=' + item.productType,
                            })
                        } else {
                            this.checkLoginToJump('/pages/realIdent/index')
                        }
                    }
                    return
                }
                common.showToast('次数已用完')
                return
            }

            if (item.nowOrderStatus == 1 && item.needReserve == 0 ||
                item.nowOrderStatus == 3 && item.needReserve == 0 ||
                item.nowOrderStatus == 6 && item.needReserve == 0 ||
                item.nowOrderStatus == 7 && item.needReserve == 0 ||
                item.nowOrderStatus == 8 && item.needReserve == 0) {
                item.statusNames = '预约'
                wx.navigateTo({
                    url: '/pages/goYuyue/yuYue/index?productId=' + that.data.objs.productId +
                        '&cardId=' + that.data.objs.cardId +
                        '&productType=' + that.data.objs.productType,
                })
            } else if (item.needReserve == 1 && item.nowOrderStatus == 1) {
                item.statusNames = '去使用'
                if (this.data.userInfo && this.data.userInfo.isRealname) {

                    wx.navigateTo({
                        url: '/packageA/pages/indexnian/qrcode/qrcode?cardId=' +
                            item.cardId + '&productId=' +
                            item.productId + '&imgCard=' + that.data.cardImage +
                            '&imgurl=' + item.productImage +
                            '&productName=' + item.productName +
                            '&pid_name=' + item.pid_name +
                            '&productType=' + item.productType,
                    })
                } else {
                    this.setData({
                        isRuleTrue: true
                    })
                }
            } else if (item.needReserve == 1 && item.nowOrderStatus == 10) {
                item.statusNames = '去使用'
                if (this.data.userInfo && this.data.userInfo.isRealname) {

                    wx.navigateTo({
                        url: '/packageA/pages/indexnian/qrcode/qrcode?cardId=' +
                            item.cardId + '&productId=' +
                            item.productId + '&imgCard=' + that.data.cardImage +
                            '&imgurl=' + item.productImage +
                            '&productName=' + item.productName +
                            '&pid_name=' + item.pid_name +
                            '&productType=' + item.productType,
                    })
                } else {
                    this.setData({
                        isRuleTrue: true
                    })
                }
            } else if (item.nowOrderStatus == 2 && item.needReserve == 0) {
                item.statusNames = '去核销'
                wx.navigateTo({
                    url: '/pages/ScenicArea/CardETicket/index?orderNo=' + item.orderNo,
                })
            } else if (item.nowOrderStatus == 5) {
                item.statusNames = '去评价'
                wx.navigateTo({
                    url: '/pages/ScenicArea/NianCardOrder/Cardcomment/Cardcomment?orderNo=' + item.orderNo,
                })
            } else if (item.nowOrderStatus == 10 && item.needReserve == 0) {
                item.statusNames = '预约'
                wx.navigateTo({
                    url: '/pages/goYuyue/yuYue/index?productId=' + that.data.objs.productId +
                        '&cardId=' + that.data.objs.cardId +
                        '&productType=' + that.data.objs.productType,
                })
            } else if (item.nowOrderStatus == null && item.needReserve == 0) {
                item.statusNames = '预约'
                wx.navigateTo({
                    url: '/pages/goYuyue/yuYue/index?productId=' + that.data.objs.productId +
                        '&cardId=' + that.data.objs.cardId +
                        '&productType=' + that.data.objs.productType,
                })
            } else if (item.nowOrderStatus == null && item.needReserve == 1) {
                item.statusNames = '去使用'
                if (this.data.userInfo && this.data.userInfo.isRealname) {
                    wx.navigateTo({
                        url: '/packageA/pages/indexnian/qrcode/qrcode?cardId=' +
                            item.cardId + '&productId=' +
                            item.productId + '&imgCard=' + that.data.cardImage +
                            '&imgurl=' + item.productImage +
                            '&productName=' + item.productName +
                            '&pid_name=' + item.pid_name +
                            '&productType=' + item.productType,
                    })
                } else {
                    this.setData({
                        isRuleTrue: true
                    })
                }
            }
        })
    },

    // 时间戳
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    onCha(event) {
        // event.detail 的值为当前选中项的索引
        this.setData({
            active: event.detail
        });
        if (this.data.active == 0) {
            var url = "/packageA/pages/indexnian/indexni?act=" + this.data.active
        } else {
            var url = "/pages/myNSelf/Index/index?act=" + this.data.active
        }
        wx.redirectTo({
            url: url,
        })
    },

    toLogin() { // 去登陆
        common.showLoginPage()
    },

    goBack() {
        wx.redirectTo({
            url: '/pages/mySelf/Index/index',
        })
    },
    // 我购买会员卡列表接口-------------------------------------------------------------------------------
    cardsList() {
        var that = this
        common.get('/userAnnualCard/getUserCardProductList', {
            userId: that.data.userInfo.id,
            token: that.data.token
        }, res => {
            if (res.status === 200) {
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].validTime = that.time(res.data[i].validTime)
                }
                // res.data= res.data.reverse()
                that.setData({
                    nianList: res.data
                }, () => {
                    if (that.data.nianList.length) {
                        that.typeList(that.data.nianList[0].annualCardId) //轮播第一条数据
                        that.setData({
                            id: that.data.nianList[0].annualCardId,
                            times: that.data.nianList[0].validTime,
                            cardImage: that.data.nianList[0].cardImage,
                            merchantPhone: that.data.nianList[0].merchantPhone,
                        }, () => {
                            that.Nian_ca()
                        })
                    }
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    // 轮播切换获取数据
    getCurrent(e) {
        var that = this
        var id = e.detail.currentItemId
        var time = this.data.nianList.find(item => item.annualCardId == id)
        console.log(time)
        this.setData({
            id,
            cardImage: time.cardImage,
            times: time.validTime
        }, () => {
            this.typeList(id)
            that.Nian_ca()
        })

    },
    // 会员卡可享权益
    Nian_ca() {
        var that = this
        common.get('/userAnnualCard/getCardProductListForApplets', {
            cardId: that.data.id,
            productType: "",
            userId: that.data.userInfo.id,
            token: that.data.token
        }, res => {
            console.log(res.data, "ceshishi")
            if (res.status === 200) {
                if (that.data.id == 7) {
                    // var items = {
                    //     discount: 0, //免费
                    //     frequency: 12,
                    //     productName: "中国石油加油券（联系客服）",
                    //     singleValue: 15,
                    // }
                    var itemss = {
                        discount: 0, //免费
                        frequency: 1,
                        productName: "中国移动咪咕视频会员(联系客服)",
                        singleValue: 180,
                    }
                    res.data.unshift(itemss)
                }

                for (var i = 0, len = res.data.length; i < len; i++) {
                    res.data[i].discount = (res.data[i].discount * 10).toFixed(1)
                    res.data[i].num_string = res.data[i].discount.toString()
                    if (res.data[i].num_string.indexOf('.') != -1) { //包含
                        res.data[i].len = res.data[i].num_string.split(".")[1]
                        res.data[i].newnum = 0
                        if (res.data[i].len != 0) {
                            res.data[i].newnum = res.data[i].discount
                        } else {
                            res.data[i].newnum = res.data[i].num_string.split(".")[0]
                        }

                    }
                }
                that.setData({
                    totalArrs: res.data
                }, () => {
                    var pagecount = 1 //默认第一页 
                    var result = [];
                    for (var i = 0, len = res.data.length; i < len; i += 5) {
                        result.push(res.data.slice(i, i + 5));
                    }
                    if (pagecount == 1) {
                        if (result[0]) {
                            that.setData({
                                totalArr: result,
                                gouList: result[0],
                                pagecount: pagecount,
                                showss: true
                            })
                        } else {
                            that.setData({
                                totalArr: result,
                                gouList: [],
                                pagecount: pagecount
                            })
                        }
                    }
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })

    },
    onChange(event) {
        console.log("点击")
        console.log(event)
        this.cardsList_two(event.detail.name)

    },
    // 会员卡详情下面的列表会员卡可享权益
    cardsList_two(pid) {
        console.log(pid, "44444")
        var that = this
        common.get('/userAnnualCard/getCardProductListForApplets', {
            cardId: that.data.id,
            productType: pid,
            userId: that.data.userInfo.id,
            token: that.data.token
        }, res => {
            console.log(res.data, "6666666")
            if (res.status === 200) {
                console.log(that.data.typeList)
                if (that.data.typeList.length > 0) {
                    var ids = that.data.typeList.find((item) => {
                        return item.id == pid
                    })
                }
                var newArr = res.data.map((item, index, arr) => {
                    if (that.data.typeList.length > 0) {
                        item['pid_name'] = ids.name
                        item['imageUrl'] = ids.imageUrl
                        item['avgScore'] = item['avgScore'] ? item['avgScore'].toFixed(1) : item['avgScore']
                    }
                    // 进行判断
                    if (!item.cardProductType) {
                        if (item.nowOrderStatus == 1 && item.needReserve == 0) {
                            item.statusNames = '预约'
                            console.log("符合", item)
                        } else if (item.needReserve == 1 && item.nowOrderStatus == 1) {
                            item.statusNames = '去使用'
                        } else if (item.needReserve == 1 && item.nowOrderStatus == 10) {
                            item.statusNames = '去使用'
                        } else if (item.nowOrderStatus == 2 && item.needReserve == 0) {
                            item.statusNames = '去核销'
                        } else if (item.nowOrderStatus == 3 && item.needReserve == 0) {
                            // item.statusNames = '已过期'
                            item.statusNames = '预约'
                        } else if (item.nowOrderStatus == 5) {
                            item.statusNames = '去评价'
                        } else if (item.nowOrderStatus == 6) {
                            // item.statusNames = '交易关闭'
                            item.statusNames = '预约'
                        } else if (item.nowOrderStatus == 7) {
                            // item.statusNames = '已退款'
                            item.statusNames = '预约'
                        } else if (item.nowOrderStatus == 8) {
                            // item.statusNames = '退款中'
                            item.statusNames = '预约'
                        } else if (item.nowOrderStatus == 9) {
                            item.statusNames = '出票中'
                        } else if (item.nowOrderStatus == 10 && item.needReserve == 0) {
                            item.statusNames = '预约'
                        } else if (item.nowOrderStatus == null && item.needReserve == 0) {
                            item.statusNames = '预约'
                        } else if (item.nowOrderStatus == null && item.needReserve == 1) {
                            item.statusNames = '去使用'
                        }
                        return item
                    } else {
                        item.statusNames = '购买'
                        return item
                    }
                })
                // newArr.push()
                that.setData({
                    nianLists: newArr
                }, () => {
                    console.log("下面的测试数据", that.data.nianLists)
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },

    // 拨打客服电话
    calling() {
        wx.makePhoneCall({
            phoneNumber: this.data.merchantPhone,
        })
    },
    // 权益类型
    typeList(id) {
        var that = this
        common.get('/store/getStoreTypeListForCard', {
            cardId: id
        }, res => {
            if (res.status === 200) {

                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].id = res.data[i].id.toString()
                }
                if (res.data.length > 0) {
                    that.cardsList_two(res.data[0].id) //调取权益列表
                } else {
                    var kong = ''
                    that.cardsList_two(kong) //调取权益列表
                }
                that.setData({
                    typeList: res.data
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    // 查看更多  
    click_data() {
        var pageCount = this.data.pagecount + 1
        if (this.data.totalArr.length == pageCount) {
            this.setData({
                showss: false
            })
        }
        if (this.data.totalArr[pageCount - 1]) {
            this.setData({
                gouList: [...this.data.gouList, ...this.data.totalArr[pageCount - 1]],
                pagecount: pageCount,
            }, () => {})
        }
    },
    click_shou() {
        this.setData({
            gouList: this.data.totalArr[0],
            showss: true,
            pagecount: 1,
        })
    },
    click_detail(e) {
        console.log(e.currentTarget.dataset.item)
        var id = e.currentTarget.dataset.item
    },
    onLoad(opt) {
        var that = this
        //获取胶囊位置
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
        var windowHeight = wx.getSystemInfoSync().windowHeight
        var windowWidth = wx.getSystemInfoSync().windowWidth
        this.setData({
            scroll_height: windowHeight * 750 / windowWidth - 200
        })
        //  获取个人信息
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token
                }, function () {
                    this.cardsList() //会员卡列表
                })
            } else {
                that.setData({
                    userInfo: null,
                    token: '',
                })
            }
        }, true)
        setTimeout(() => {
            this.setData({
                sho: true
            })
        }, 1000);
        var pages = getCurrentPages();
        var pagerouter = pages[pages.length - 2].route
        if (pagerouter == 'pages/mySelf/Index/index' || pagerouter == 'pages/goYuyue/yuYue/index') {
            this.setData({
                flag_tab: false
            })
        }
        if (opt.act) {
            this.setData({
                active: parseInt(opt.act)
            })
        }
    },
    //  标签切换 
    onReady: function () {

        setTimeout(() => {
            this.setData({
                sho: true
            })
            this.selectComponent('#vanTabs').resize()
        }, 1000);
    },
    onShareAppMessage: function () {
        return {
            title: '会员卡',
            path: '/packageA/pages/indexnian/indexni',
            success: (res) => {
                // 分享成功
            },
            fail: (res) => {
                // 分享失败
            }
        }
    },
})